// page/one/index.js
var Bmob = require('../../utils/bmob.js');
var app = getApp()
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var wxApi = require('../../es6-promise/utils/wxApi.js')
var wxRequest = require('../../es6-promise/utils/wxRequest.js')
Page({
    data: {
        flagCurrentNavIndex: 0, // 全部/品牌
        typeNameChecked: '', // 选择的品牌名称
        flagTypeShow: false, // 品牌展开/关闭flag
        carList: [],
        typeList: [],
        typeId: 0, // all/class
        isCheckedType: false,
        postsList: [],
        isLastPage: false,
        page: 1,
        search: '',
        categories: 0,
        showerror: "none",
        showCategoryName: "",
        categoryName: "",
        showallDisplay: "block",
        displayHeader: "none",
        displaySwiper: "none",
        floatDisplay: "none"
    },
    //所有案例
    handleAllCase:function () {
      var me = this;
        // 不做无效请求
        let flagCurrentNavIndex = this.data.flagCurrentNavIndex
        if (flagCurrentNavIndex === 0) {
            return
        }
        this.setData({
            flagCurrentNavIndex: 0,
            typeNameChecked: '',
            flagTypeShow: false,
            typeId: 0,
            isCheckedType: false
        })
        wx.setNavigationBarTitle({
            title: '所有案例'
        })
        this.fetchPostsData({
          categories: me.data.typeId
        });
    },
    // 品牌点击展开/关闭
    handleTypeNav:function(event) {
        this.setData({
            flagTypeShow: !this.data.flagTypeShow
        })
    },
    // 案例类型选择
    handleTypeCheck: function(event) {
        var me = this;
        let flagCurrentNavIndex = this.data.flagCurrentNavIndex;
        let currentTypeId = this.data.typeId;
        let data = event.currentTarget.dataset;
        let typeName = data.typeName;
        let typeId = data.typeId;
        let typeCode = data.typeCode;
        // 不做无效请求
        if (flagCurrentNavIndex === 1 && currentTypeId === typeId) {
            return
        }
        
        this.setData({
            typeNameChecked: typeName,
            flagCurrentNavIndex: 1,
            typeId: typeId,
            typeCode: typeCode,
            isCheckedType: true
        })
        wx.setNavigationBarTitle({
            title: '案例-' + typeName
        })

        this.fetchPostsData({
          categories: me.data.typeId
        })
    },
    // 抓取案例类型数据
    fetchTypeList: function () {
      var me = this;
      var CaseType = Bmob.Object.extend("CaseType");
      var query = new Bmob.Query(CaseType);
      query.ascending("order");
      query.equalTo("isShow", true);
      query.find({
        success: function (results) {
          // 循环处理查询到的数据
          var typeList = [];
          for (var i = 0; i < results.length; i++) {
            var obj = results[i];
            typeList.push({
              typeId: obj.get("typeId"),
              typeName: obj.get("name"),
              typeCode: obj.get("code"),
              typeLogo: obj.get("logo")
            });
          }
          me.setData({
            typeList: typeList
          });
          wx.setStorageSync("caseTypes", typeList);
        },
        error: function (error) {
          console.error(error, "查询失败");
        }
      });
    },
    onLoad: function (params) {
        var me = this;
        wx.setNavigationBarTitle({
            title: '所有案例'
        });
        wx.getSystemInfo({
            success: function (res) {
                me.setData({
                    scrollHeight: res.windowHeight - 65
                });
            }
        });
        // init data
        let typeList = wx.getStorageSync("caseTypes");
        if (!typeList) {
            this.fetchTypeList();
        }else{
            this.setData({
                typeList: typeList
            })
        }
        if(params && params.typeCode) {
            this.setData({
                typeNameChecked: params.typeName,
                flagCurrentNavIndex: 1,
                typeId: params.typeId,
                typeCode: params.typeCode,
                hasMore: true,
                caseList: [],//切换类型，清空原有案例
                isCheckedType: true
            })
            wx.setNavigationBarTitle({
                title: '案例-' + params.typeName
            })
        }
        this.fetchPostsData({
          categories:me.data.typeId
        })
    },
    //获取文章列表数据
    fetchPostsData: function (data) {
      var self = this;
      if (!data) data = {};
      if (!data.page) data.page = 1;
      if (!data.categories) {
        data.categories = '';
        for (var i = 0; i < self.data.typeList.length; i++) {
          data.categories = data.categories + ',' + self.data.typeList[i].typeId;
        }
        data.categories = data.categories.substring(1);
        
      }
      if (!data.search) data.search = '';
      if (data.page === 1) {
        self.setData({
          postsList: []
        });
      };
      wx.showLoading({
        title: '正在加载',
        mask: true
      });
      var getPostsRequest = wxRequest.getRequest(Api.getPosts(data));
      getPostsRequest
        .then(response => {
          if (response.statusCode === 200) {

            if (response.data.length < 6) {
              self.setData({
                isLastPage: true
              });
            }
            self.setData({
              floatDisplay: "block",
              postsList: self.data.postsList.concat(response.data.map(function (item) {

                var strdate = item.date
                if (item.category_name != null) {

                  item.categoryImage = "../../images/category.png";
                }
                else {
                  item.categoryImage = "";
                }

                if (item.post_thumbnail_image == null || item.post_thumbnail_image == '') {
                  item.post_thumbnail_image = Api.getContentFirstImage(item.content.rendered);
                }
                item.date = util.cutstr(strdate, 10, 1);
                return item;
              })),

            });
            setTimeout(function () {
              wx.hideLoading();
            }, 900);
          }
          else {
            if (response.data.code == "rest_post_invalid_page_number") {
              self.setData({
                isLastPage: true
              });
              wx.showToast({
                title: '没有更多内容',
                mask: false,
                duration: 1500
              });
            }
            else {
              wx.showToast({
                title: response.data.message,
                duration: 1500
              })
            }
          }


        })
        .catch(function (response) {
          if (data.page == 1) {

            self.setData({
              showerror: "block",
              floatDisplay: "none"
            });

          }
          else {
            wx.showModal({
              title: '加载失败',
              content: '加载数据失败,请重试.',
              showCancel: false,
            });
            self.setData({
              page: data.page - 1
            });
          }

        })
        .finally(function (response) {
          wx.hideLoading();
          wx.stopPullDownRefresh();
        });
    },
    //加载分页
    loadMore: function (e) {

      var self = this;
      if (!self.data.isLastPage) {
        self.setData({
          page: self.data.page + 1
        });
        //console.log('当前页' + self.data.page);
        this.fetchPostsData(self.data);
      }
      else {
        wx.showToast({
          title: '没有更多内容',
          mask: false,
          duration: 1000
        });
      }
    },
    // 跳转至查看文章详情
    redictDetail: function (e) {
      // console.log('查看文章');
      var id = e.currentTarget.id,
        url = '../detail/detail?id=' + id;
      wx.navigateTo({
        url: url
      })
    },
    //返回首页
    redictHome: function (e) {
      //console.log('查看某类别下的文章');  
      var id = e.currentTarget.dataset.id,
        url = '/pages/case/case';
      wx.switchTab({
        url: url
      });
    }
})
